<template>
  <div class="sshForm" v-show="sshFormVisible" @click.self="handleMaskClick">
    <div class="login-main">
      <p class="login-logo" ref="loginLogoRef">连接主机</p>

      <div class="login-form">
        <el-form :model="sessionForm" label-width="80px" ref="sessionFormRef" :rules="loginRules">
          <el-row justify="start">
            <el-col :span="12">
              <el-form-item label="连接名称" prop="name">
                <el-input v-model="sessionForm.name" placeholder="连接名称">
                </el-input>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="IP" prop="IPAddr">
                <el-input v-model="sessionForm.IPAddr" placeholder="IP地址或域名">
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="用户" prop="username">
                <el-input v-model="sessionForm.username" placeholder="用户名">
                </el-input>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="密码" prop="password">
                <el-input v-model="sessionForm.password" placeholder="密码" type="password">
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="15">
              <el-form-item label="密钥">
                <input id="file" type="file" ref="fileRef" @change="fileChanged"/><br/>
                <input type="button" value="选择密钥" @click="handleFileSelect" ref="fileBtnRef" class="textEllipsis"/>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <div class="login-bottom">
        <el-button type="primary" style="width: 200px" size="large" @click="handleConnect">连接</el-button>
        <el-button type="primary" style="width: 100px" size="large" @click="clearForm">清空</el-button>
        <p class="tip">云主机需要私钥</p>
        <p class="tip">虚拟机不需要</p>
      </div>
    </div>
  </div>
</template>

<script>
import {validateDomain, validateIPAddr} from '@/utils/validate'
import Panel from "@/components/Panel/Panel.vue";
import {mapState} from 'vuex'
import {utf8_to_b64} from '@/utils/utils'

export default {
  components: {Panel},
  computed: {
    ...mapState({
      sshFormVisible: state => state.ssh.sshFormVisible
    }),
  },

  data() {
    const validateIP = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入IP地址'))
      } else {
        if (validateDomain(value) && validateIPAddr(value)) {
          callback()
        } else {
          callback(new Error('请输入正确的IP/域名'))
        }
      }
    }

    return {
      options: [
        {label: 'TELNEL', value: 'telnet'},
        {label: 'RLOGIN', value: 'rlogin'},
        {label: 'SSH', value: 'ssh'},
        {label: 'SFTP', value: 'sftp'},
        {label: 'SERIAL', value: 'serial'},
        {label: 'LOCAL', value: 'local'},
        {label: 'FTP', value: 'ftp'},
      ],

      loginRules: {
        name: [
          {required: true, trigger: "blur", message: "请输入连接名称"}
        ],
        IPAddr: [
          {validator: validateIP, trigger: "blur"},
          {required: true, trigger: "blur", message: "请输入IP地址"}
        ],
        username: [
          {required: true, trigger: "blur", message: "请输入您的账号"}
        ],
        password: [
          {required: true, trigger: "blur", message: "请输入您的密码"}
        ],
      },

      sessionForm: {
        name: '',
        IPAddr: "",
        username: "",
        password: ""
      },
    }
  },

  methods: {
    clearForm() {
      this.$refs.sessionFormRef.resetFields()
    },

    handleConnect() {
      this.$refs.sessionFormRef.validate(valid => {
        if (!valid) return;
        let obj = {
          ...this.sessionForm,
          title: this.sessionForm.name,
          path: '/os/' + this.sessionForm.name + '?path=' + utf8_to_b64('/'),
          lastPath: ''
        }

        this.$store.dispatch('addVisitedView', obj);
        this.$store.dispatch('toggleSSHFormVisible');

        this.$store.dispatch("Connect", this.sessionForm)
            .then((res) => {
              this.$router.push({path: obj.path, query: {path: utf8_to_b64('/')}})
            })

        // 将会话连接信息保存在本地
        var sessions = this.$cache.session.getJSON('session');
        if (sessions === undefined || sessions.length === 0) {
          sessions = []
          sessions.push(obj)
        } else {
          if (sessions.some(s => s.name === obj.name)) {
            this.$router.push(obj.path);
            return;
          }
          sessions.push(obj)
        }
        this.$cache.session.remove('session')
        this.$cache.session.setJSON('session', sessions)
      })

    },

    handleMaskClick() {
      this.$store.dispatch('toggleSSHFormVisible');
    },

    handleFileSelect() {
      this.$refs.fileRef.click()
    },

    async fileChanged(input) {
      let file = this.$refs.fileRef.files[0]
      this.$refs.fileBtnRef.value = file.name
      let reader = new FileReader();
      const content = await this.waitReader(file)
      this.$store.dispatch('setPrivaryKey', content)
    },

    waitReader(file) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader()
        reader.readAsText(file, 'UTF-8')
        reader.onload = function (evt) {
          const fileString = evt.target.result
          fileString ? resolve(fileString) : reject(evt)
        }
      })
    }
    //
  }
}
</script>

<style scoped lang="scss">
.sshForm {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100vh;
  background-color: rgba(0, 0, 0, .5);
  display: flex;
  align-items: center;
  justify-content: center;
}

.login-main {
  padding: 10px;
  border-radius: 20px;
  background-color: rgba(255, 255, 255, .8);
}

.login-logo {
  font-size: 30px;
  text-align: center;
  font-family: Sans-serif;
  width: 100%;
}

.login-form {
  padding: 10px 20px;
  padding-bottom: 0px;
}

.tip {
  font-family: Monospace;
  font-weight: bold;
  margin-top: 5px;
  text-align: center;
}

.login-bottom {
  width: 100%;
  text-align: center;
}

#file {
  display: none;
}

input[type='button'] {
  width: 100px;
  height: 30px;
  padding: 5px 10px;
  background-color: #409eff;
  border: none;
  color: #fff;
  border-radius: 5px;
}
</style>
